package logique.outils;


import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public abstract class Parseur {

	protected File fichier;

	protected Parseur() {
	}

	protected void afficher (double[] tab) {
		System.out.print("(");
		for (double d : tab) {
			System.out.print(d + ", ");
		}
		System.out.println(")");
	}

	protected void afficher (double[][] tab) {
		System.out.println("[");
		for (double[] dt : tab) {
			afficher(dt);
		}
		System.out.println("]");
	}

	protected int lireEntier (String ligne) {
		try {
			Pattern p = Pattern.compile("\\s*([0-9]+).*", Pattern.CASE_INSENSITIVE
					| Pattern.COMMENTS | Pattern.CANON_EQ);
			Matcher m = p.matcher(ligne);
			if (m.matches() && m.groupCount() > 0) {
				return Integer.parseInt(m.group(1));
			}
		} catch (PatternSyntaxException pse) {
			pse.printStackTrace();
		} catch (NumberFormatException nfe){
		}
		return -1;
	}

	private static final String lireReel   = "(-?[0-9]*,[0-9]+|-?[0-9]*\\.[0-9]+|-?[0-9]+)";
	
	protected CoupleReels lireDoubles (String ligne) {
		try {
			Pattern p = Pattern.compile("\\s*"+lireReel+"\\s*"+lireReel+".*", Pattern.CASE_INSENSITIVE
					| Pattern.COMMENTS | Pattern.CANON_EQ);
			Matcher m = p.matcher(ligne);
			if (m.matches() && m.groupCount() > 0) {
				return new CoupleReels(Double.parseDouble(m.group(1).replace(',', '.')), Double.parseDouble(m.group(2).replace(',', '.')));
			}
		} catch (PatternSyntaxException pse) {
			pse.printStackTrace();
		} catch (NumberFormatException nfe){
		}
		return null;
	}

	protected TripletBelleville lireReelIndice (String ligne) {
		try {

			Pattern p = Pattern.compile("\\s*(-?[0-9]+)[^0-9-]*(-?[0-9]+)[^0-9.,-]*"+lireReel+".*", Pattern.CASE_INSENSITIVE
					| Pattern.COMMENTS | Pattern.CANON_EQ);
			Matcher m = p.matcher(ligne);
			if (m.matches() && m.groupCount() > 0) {
				return new TripletBelleville(
						Integer.parseInt(m.group(1)), 
						Integer.parseInt(m.group(2)), 
						Double.parseDouble(m.group(3).replace(',', '.'))
				);
			}
		} catch (PatternSyntaxException pse) {
			pse.printStackTrace();
		} catch (NumberFormatException nfe){
		}
		return null;
	}

	class CoupleReels {
		public double x, y;
		CoupleReels (double x, double y) {
			this.x = x; this.y = y;
		}
		public String toString () {
			return "(" + x + ", " + y + ")";
		}
	}

	class TripletBelleville {
		public int x, y;
		public double z;
		TripletBelleville (int x, int y, double z) {
			if (x < y) {
				this.x = x; this.y = y;
			} else {
				this.x = y; this.y = x;
			}
			this.z = z;
		}
		public String toString () {
			return "(" + x + ", " + y + ", "+ z + ")";
		}
		public boolean estCorrect (int n) {
			return x > 0 && x <= n && y > 0 && y <= n;
		}
	}
}